package org.leon.builder;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.leon.io.Resource;
import org.leon.pojo.Configuration;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * Created by leon.L on 2019/12/24.
 * Desc :
 */
public class XmlConfigurationBuilder {

    private Configuration configuration;

    public XmlConfigurationBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 改方法解析 sqlMapconfig.xml 并封装成 Configuration
     * @param inputStream
     * @return
     */
    public Configuration parseXml(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> propertyList = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        propertyList.forEach(ele -> {
            String name = ele.attributeValue("name");
            String value = ele.attributeValue("value");
            properties.setProperty(name, value);
        });

        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("url"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        this.configuration.setDataSource(dataSource);

        // 获取 mapper.xml 集合并解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element ele : mapperList) {
            String mapperPath = ele.attributeValue("resource");
            InputStream mapperStream = Resource.getResourceAsStream(mapperPath);

            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
            xmlMapperBuilder.parse(mapperStream);
        }
        return this.configuration;
    }

}
